﻿using System.Linq;
using System.Threading;
using RayDen.Library.Core;
using RayDen.Library.Core.Primitives;
using RayDen.RayEngine;
using RayDen.RayEngine.Core.Types;
using RayDen.RayEngine.Data;

namespace PathEngine
{
    public struct PrimitiveHit
    {
        public uint PrimitiveId;
        public float Distance, U, V;
    }

    public class IntersectionData
    {
        
    }

    public class RayCollection : RayBufferBase<Ray, PrimitiveHit>
    {
        public static int collectionId = 100;
        public int CollectionId;
        public bool traced;

        public int HitCount
        {
            get { return this.rayHits.Count(item => item.PrimitiveId != RayBuffer.NotHit); }
        }

        public RayCollection(int size) : base(size)
        {
            CollectionId = (collectionId=Interlocked.Increment(ref collectionId));
        }


        public override bool IsHit(int index)
        {
            return this.rayHits[index].PrimitiveId != NotHit;
        }

        public override void Reset()
        {
            base.Reset();
            traced = false;
        }

        public bool IsBlocked(int index, int eyeRayIndex)
        {
            var rayHit = this.rayHits[index].PrimitiveId != NotHit;
            var samePrim = this.rayHits[index].PrimitiveId == this.rayHits[eyeRayIndex].PrimitiveId;
            return rayHit && !samePrim;
        }

        public void GetHitPoint(int index, out Point result)
        {
            result = this.RaysInfo[index].Point(this.rayHits[index].Distance);
        }

        public void UpdateHit(int rayId, ref PrimitiveHit rayHit)
        {
            for (int i = 0; i < RaysInfo.Length; i++)
            {
                if (RaysInfo[i].Id == rayId)
                {
                    rayHits[i] = rayHit;
                }
            }

            //FIND HIT BY RAYID
            //UPDATE WITH REF
        }
    }
}